package com.zhongwang.mms.module.tool.listner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import com.zhongwang.mms.module.tool.callback.OffEquipmentCallBack;
import com.zhongwang.mms.module.tool.dao.AccOffEquipmentDao;
import com.zhongwang.mms.module.tool.model.ReportAccOffEquipmentModel;
import com.zhongwang.mms.util.ShiroUtils;

import java.util.ArrayList;
import java.util.List;
    /**
     * @Description: 设备台账信息 导入 listener
     *
     * @Author: China.yw
     * @Date: 2020/04/24 9:38
     */
    public class OffEquipmentListener extends AnalysisEventListener<ReportAccOffEquipmentModel> {
        private AccOffEquipmentDao equipmentDao;
        private OffEquipmentCallBack equipmentCallBack;
        private List<ReportAccOffEquipmentModel> reportEquipmentModels = new ArrayList<>();


        public OffEquipmentListener(AccOffEquipmentDao reportPlanDao,
                                    OffEquipmentCallBack equipmentCallBack) {
            this.equipmentDao = reportPlanDao;
            this.equipmentCallBack = equipmentCallBack;

        }

        @Override
        public void invoke(ReportAccOffEquipmentModel data, AnalysisContext context) {

            /**
             * 验证 资产编号、设备名称、数量不可以为空，其他的都可以为空。
             */
            if (data.getOffEqCode() == null || data.getOffEqName() == null
                    || data.getOffEqmUnm() == null) {
                //不合格的数据往这个里放。
                reportEquipmentModels.add(data);
                return;
            }
            /**
             * 设置人员信息和删除标识
             */
            data.setOffIsdelete(0);
            ReportAccOffEquipmentModel keyModel = new ReportAccOffEquipmentModel();
            //根据资产编号查询
            keyModel.setOffEqCode(data.getOffEqCode());
            ReportAccOffEquipmentModel checkModel = equipmentDao.selectAccOffEquipment(keyModel);
            if (checkModel != null) {
                //更新参数的model并且赋值
                data.setOffId(checkModel.getOffId());

                //执行修改，不存在序号的问题。
                data.setOffUpdUser(ShiroUtils.getUser().getName());
                equipmentDao.update(data);
            } else {
                //需要查询最大的序号，间隔为10。
                data.setOffSortNum(equipmentDao.selectMaxNum());
                data.setOffCreUser(ShiroUtils.getUser().getName());
                data.setOffUpdUser(ShiroUtils.getUser().getName());
                equipmentDao.insert(data);
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            if (reportEquipmentModels.size() > 0) {
                equipmentCallBack.onWarning(reportEquipmentModels);
            } else {
                equipmentCallBack.onSuccess();
            }
        }

        @Override
        public void onException(Exception exception, AnalysisContext context) {
            equipmentCallBack.onError();
        }
    }

